import { PlusOutlined, ExclamationCircleOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Menu, Modal, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import RouteForm from './components/RouteForm';
import HeaderDropdown from '@/components/HeaderDropdown/index';
import { services } from '@/network/api';
import * as icons from '@ant-design/icons';
import utils from '@/utils/index';
const { confirm } = Modal;

type formState = {
  visible?: boolean;
  id?: any;
  pid?: any;
  ptype?: any;
};

type col = {
  id: number;
  name: string;
  type: number;
  createDate: string;
  icon: string;
  access: any;
};

const TableList: React.FC = (props: any) => {
  const { route } = props;
  const [formState, setFormState] = useState<formState>({
    visible: false,
    id: null,
    pid: null,
    ptype: null,
  });
  const [selectedRows, setSelectedRows] = useState<col[]>([]);
  const actionRef = useRef<ActionType>();
  const delAccessList = () => {
    confirm({
      title: '确认删除路由?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        const delAccessList = async () => {
          await services.delRouteList({
            idList: selectedRows.map((item) => {
              return item.id;
            }),
          });
          setTimeout(() => {
            actionRef?.current?.clearSelected?.();
            actionRef?.current?.reload();
          }, 300);
        };
        delAccessList();
      },
    });
  };

  const columns: ProColumns<col>[] = [
    {
      title: '路由id',
      dataIndex: 'id',
      // sorter: true,
    },
    {
      title: '路由权限名称',
      dataIndex: 'name',
      // sorter: true,
    },
    {
      title: '路由路径',
      dataIndex: 'path',
      // sorter: true,
    },
    {
      title: '角色',
      dataIndex: 'access',
      hideInSearch: true,
      render: (_, record) => {
        return record?.access?.map((item: any) => {
          return <Tag color="blue">{item?.name}</Tag>;
        });
      },
    },
    {
      title: '角色',
      dataIndex: 'accessIds',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        mode: 'multiple',
      },
      request: async (params) => {
        let res = await services.getAccessList({ noPagination: true, noMsg: true, state: 1 });
        return res?.data?.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      },
    },
    {
      title: '路由类型',
      dataIndex: 'type',
      // sorter: true,
      valueEnum: {
        1: {
          text: '菜单',
        },
        2: {
          text: '页面',
        },
        3: {
          text: '按钮',
        },
      },
    },
    {
      title: '创建日期',
      dataIndex: 'createDate',
      valueType: 'dateTime',
      // sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建日期范围',
      dataIndex: 'createDateRange',
      valueType: 'dateTimeRange',
      hideInTable: true,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      valueType: 'option',
      render: (_, record) => {
        return [!!record.icon && React.createElement(icons[record.icon])];
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return [
          route.checkBtn('edit') && (
            <a
              onClick={() => {
                setFormState({ ...formState, visible: true, id: record.id });
              }}
            >
              修改
            </a>
          ),
          route.checkBtn('delete') && (
            <a
              onClick={() => {
                confirm({
                  title: '确认删除路由?',
                  icon: <ExclamationCircleOutlined />,
                  onOk() {
                    const delRouteList = async () => {
                      await services.delRouteList({ idList: [record.id] });
                      setTimeout(() => {
                        actionRef?.current?.reload();
                      }, 300);
                    };
                    delRouteList();
                  },
                });
              }}
            >
              删除
            </a>
          ),
          route.checkBtn('add') && record.type !== 3 && (
            <a
              onClick={() => {
                setFormState({
                  ...formState,
                  visible: true,
                  pid: record.id,
                  ptype: record.type,
                  id: null,
                });
              }}
            >
              新增
            </a>
          ),
          <HeaderDropdown overlay={<Menu selectedKeys={[]}></Menu>}>
            <a>
              <EllipsisOutlined />
            </a>
          </HeaderDropdown>,
        ];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        search={false}
        // search={{
        //   labelWidth: 120,
        // }}
        pagination={false}
        headerTitle="路由管理"
        actionRef={actionRef}
        rowKey="id"
        toolbar={{}}
        columnsState={{
          persistenceType: 'localStorage',
          persistenceKey: 'routeTableColSet',
        }}
        toolBarRender={() => [
          route.checkBtn('add') && (
            <Button
              type="primary"
              onClick={() => {
                setFormState({ ...formState, visible: true, id: null, pid: null, ptype: null });
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ),
          route.checkBtn('delete') && (
            <Button type="primary" disabled={!selectedRows?.length} danger onClick={delAccessList}>
              <PlusOutlined /> 批量删除
            </Button>
          ),
        ]}
        request={async (param, orderParam, ...arg) => {
          return await services.getRouteTreeList({
            ...param,
            orderParam,
            noMsg: true,
            noThrottle: true,
          });
        }}
        postData={(...arg) => {
          utils.arr.shakeTreeArr(arg[0], 'children');
          return arg[0];
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <RouteForm
        {...formState}
        onVisibleChange={(visible) => {
          setFormState({ ...formState, visible });
        }}
        _onFinish={() => {
          setFormState({ ...formState, visible: false });
          setTimeout(() => {
            actionRef?.current?.reload();
          }, 300);
        }}
      />
    </PageContainer>
  );
};

export default TableList;
